package com.manor.main.fragment.community

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.ActivityUtils
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.orhanobut.logger.Logger
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.activity.WebViewActivity
import com.manor.common.custom.DrawableTextView
import com.manor.common.http.CommonHttpUtil
import com.manor.common.http.HttpCallback
import com.manor.common.http.PitUtil
import com.manor.common.utils.ClickUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.utils.WordUtil
import com.manor.common.utils.*
import com.manor.dynamic.activity.AbsDynamicActivity
import com.manor.dynamic.activity.AbsDynamicActivity.isOnclick
import com.manor.dynamic.activity.DynamicDetailsActivity
import com.manor.dynamic.activity.DynamicPublishActivity
import com.manor.dynamic.bean.CommunityDynamicBean
import com.manor.dynamic.event.DynamicDelEvent
import com.manor.dynamic.event.SubmitDynamiFinish
import com.manor.dynamic.http.DynamicHttpConsts
import com.manor.dynamic.http.DynamicHttpUtil
import com.manor.dynamic.views.AudioMp3View
import com.manor.main.R
import com.manor.main.activity.UserCenterActivity
import com.manor.main.adapter.NewCircleAdapter
import com.manor.main.bean.CommunityCityBannerBean
import com.manor.main.custom.AutoDismissDialog
import com.manor.main.http.MainHttpUtil
import com.tencent.rtmp.ITXVodPlayListener
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXVodPlayConfig
import com.tencent.rtmp.TXVodPlayer
import com.tencent.rtmp.ui.TXCloudVideoView
import com.youth.banner.Banner
import kotlinx.android.synthetic.main.fragment_circle.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 最新
 */
class NewCircleFragment : CommunityBaseFragment() {
    private var firstVisibleItem = 0
    private var lastVisibleItem = 0
    private var visibleCount = 0
    lateinit var communityDynamicAdapter: NewCircleAdapter
    private var communityCityBannerBeanList: List<CommunityCityBannerBean> = ArrayList()
    private val images = ArrayList<String>()
    private var my_position: Int = 0
    private var mPlayer: TXVodPlayer? = null
    var flvUrl: String = ""
    internal var pageNum = 1
    internal var is_Activity = true//是否在当前界面
    private var cityRefresh: Boolean = false
    private val arrayList = ArrayList<String>()



    companion object{
        fun newInstance(): NewCircleFragment {
            val args = Bundle()
            val fragment = NewCircleFragment()
            fragment.arguments = args
            return fragment
        }
    }


    override fun onSetLayoutId(): Int {
        return R.layout.fragment_circle
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mPlayer = TXVodPlayer(activity)
//        getBannerDate()
        EventBus.getDefault().register(this)
        initRecyclerView()
        getDynamicList()
        view.findViewById<ImageView>(R.id.ivAdd).setOnClickListener {
            if (ClickUtil.canClick()){
                ActivityUtils.startActivity(DynamicPublishActivity::class.java)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        is_Activity = true
        Logger.i("cityFragment-onHiddenChangedonResume")
        //开始轮播
//        mBanner?.startAutoPlay()
//        if (!cityRefresh) {
//            if (srl_city != null) {
//                srl_city.autoRefresh()
//            }
//            cityRefresh = true
//        }
        if(isOnclick&&null!=mPlayer){
            mPlayer?.resume()
        }
    }

    fun gettop() {//双击回到顶部
        recycler_view.smoothScrollToPosition(0)
    }

    private fun getBannerDate() {
        MainHttpUtil.getSide(object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0 && info.isNotEmpty()) {
                    val result = PitUtil.strGetFirst(info)
                    communityCityBannerBeanList = JSON.parseArray(result, CommunityCityBannerBean::class.java)
                    if (communityCityBannerBeanList.size > 0) {
                        if (images.size > 0) {
                            images.clear()
                        }
                        for (i in communityCityBannerBeanList.indices) {
                            images.add(communityCityBannerBeanList.get(i).image)
                        }
//                        initBanner()
                    }
                }
            }
        })
    }

    private fun initBanner() {
//        banner?.outlineProvider = object : ViewOutlineProvider() {
//            override fun getOutline(view: View, outline: Outline) {
//                outline.setRoundRect(0, 0, view.width, view.height, 30f)
//            }
//        }
//        banner?.clipToOutline = true
//        //设置图片加载器
//        banner?.setImageLoader(GlideImageLoader())
//        //设置banner?样式
//        banner?.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
//        //设置图片集合
//        banner?.setImages(images)
//        //设置banner?动画效果
//        banner?.setBannerAnimation(Transformer.DepthPage)
//        //设置自动轮播，默认为true
//        banner?.isAutoPlay(true)
//        //设置轮播时间
//        banner?.setDelayTime(2500)
//        //设置指示器位置（当banner?模式中有指示器时）
//        banner?.setIndicatorGravity(BannerConfig.CENTER)
//        //banner?设置方法全部调用完毕时最后调用
//        banner?.start()
//
//        banner?.setOnBannerListener(OnBannerListener { position ->
//            if (ClickUtil.canClick()) {
//                if (communityCityBannerBeanList.size > 0) {
//                    val title = communityCityBannerBeanList[position].title
//                    val url = communityCityBannerBeanList[position].url
//                    RouteUtil.forwardPcWeb(url, title)
//                }
//            }
//        })
    }

    //发布动态后更新当前的动态
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun updateDate(submitDynamiFinish: SubmitDynamiFinish?) {
        if (submitDynamiFinish != null) {
            val i = submitDynamiFinish.i
            Log.i("刷新下.", "..................i.......................")
            srl_city.autoRefresh()
        } else {
            Log.i("刷新下.", ".............没有数据...........................")
        }
    }

    //用户删除动态后 刷新当前页面
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDynamicDel(e: DynamicDelEvent?) {
        Logger.i("cityFragment-刷新当前页面")
//        if (e != null) {
//            srl_city.autoRefresh()
//        }
    }

    private fun initRecyclerView() {
        recycler_view.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        srl_city.setHeaderTriggerRate(0.1f)
        srl_city.setHeaderMaxDragRate(1f)
        srl_city.setHeaderHeight(60f)
        communityDynamicAdapter = NewCircleAdapter(null)
        recycler_view.adapter = communityDynamicAdapter
//        val hv1 = LayoutInflater.from(activity).inflate(R.layout.rv_header, null, false)
//        communityDynamicAdapter.addHeaderView(hv1)
//        banner = hv1.findViewById(R.id.banner)
        communityDynamicAdapter.setIOnclickListener(object : NewCircleAdapter.NewCircrle {
            //点击放大视频
            override fun clickVideo(container: FrameLayout, videoGroup: View, playView: TXCloudVideoView, img : ImageView, w:Int, h:Int) {
                (activity as AbsDynamicActivity).addPlayerGroups(container, videoGroup, playView,img,w,h)
                if (playView.tag != flvUrl) {//是否正在播放和需要播放的是一个地址
                    if (null != rl_community_audio && null != rl_community_audio?.tag) {
                        rl_community_audio?.stopVoice()
                    }
                    mPlayer?.stopPlay(true)
                    mPlayer?.setPlayerView(playView)
                    mPlayer?.setAutoPlay(true)
                    val config = TXVodPlayConfig()
                    config.setCacheFolderPath(activity?.cacheDir?.absolutePath)
                    config.setMaxCacheItems(10)
                    mPlayer?.setConfig(config)
                    mPlayer?.isLoop = true
                    flvUrl = playView.tag.toString()
                    mPlayer?.startPlay(flvUrl)
                    mPlayer?.setVodListener(object :ITXVodPlayListener {
                        override fun onNetStatus(p0: TXVodPlayer?, p1: Bundle?) {
                        }
                        override fun onPlayEvent(p0: TXVodPlayer?, p1: Int, p2: Bundle?) {
                            KLog.e("tag",p1.toString())
                            when(p1) {
                                TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION->{
                                }
                                TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED -> {//
                                    if (isVisible)
                                        mPlayer?.pause()
                                }
                            }
                        }
                    })
                } else {
                    mPlayer?.setPlayerView(playView)
                    mPlayer?.resume()

                }
            }
        })
        communityDynamicAdapter.setOnItemClickListener { adapter, view, position ->
            if (ClickUtil.canClick()) {
                if(communityDynamicBeans[position].isgg == "CPM"){
                    if(communityDynamicBeans[position].jump_url != ""){
                        WebViewActivity.forwars(activity, communityDynamicBeans[position].jump_url)
                    }
                }else {
                    my_position = position
                    val intent = Intent(activity, DynamicDetailsActivity::class.java)
                    intent.putExtra(Constants.DYNAMIC_BEAN, communityDynamicBeans[position])
                    intent.putExtra("position", position.toString() + "")
                    intent.putExtra("immortal", communityDynamicAdapter.getItem(position).userinfo.immortal + "")
                    startActivityForResult(intent, 7)
                }
            }
        }
        recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (is_Activity) {
                        autoPlayVideo(recyclerView)
                    }
                    KLog.e("tag", "停止滑动")
                } else {
                    KLog.e("tag", "开始滑动")
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
                    lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                    visibleCount = lastVisibleItem - firstVisibleItem
                    val itemTotalCount = layoutManager.getItemCount()
                    val lastChildView = layoutManager.getChildAt(layoutManager.getChildCount() - 1) ?: return
                    val lastChildBottom = lastChildView.bottom
                    val recyclerBottom = recyclerView.bottom
                    if (lastVisibleItem == itemTotalCount - 1 && lastChildBottom == recyclerBottom) {
                        if (is_shuaxin) {
                            is_shuaxin = false
                            pageNum++
                            srl_city.setEnableLoadMore(false)
                            KLog.e("getDynamicList", "自动加载")
                            getDynamicList()
                        }
                    }
                }
            }
        })
        srl_city?.setEnableAutoLoadMore(false)
        srl_city?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (is_shuaxin) {
                    pageNum++
                    srl_city?.setEnableLoadMore(false)
                    KLog.e("getDynamicList", "手动加载")
                    is_shuaxin = false
                    getDynamicList()
                }
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                if (is_shuaxin) {
                    srl_city?.setEnableRefresh(false)
                    is_shuaxin = false
                    pageNum = 1
//                    getBannerDate()
                    getDynamicList()
                }
            }
        })
        communityDynamicAdapter.addChildClickViewIds(R.id.tv_tip, R.id.tv_forward, R.id.tv_like, R.id.iv_love, R.id.iv_logo, R.id.tv_comment, R.id.rl_community_audio, R.id.im_gd)
        communityDynamicAdapter.setOnItemChildClickListener(itemChildClickListener)
    }

    var is_shuaxin: Boolean = true

    override fun onPause() {
        super.onPause()

        //结束轮播
//        mBanner?.stopAutoPlay()

        mPlayer?.pause()
        flvUrl = ""
        is_Activity = false
        if (null != rl_community_audio && null != rl_community_audio?.tag) {
            rl_community_audio?.stopVoice()
        }

    }

    override fun onInvisible() {
        super.onInvisible()
        mPlayer?.pause()
    }


    fun stopVoice() {
        mPlayer?.stopPlay(false)

        if (null != rl_community_audio && null != rl_community_audio?.tag) {
            rl_community_audio?.stopVoice()
            rl_community_audio?. resetView()
            rl_community_audio?. release()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        DynamicHttpUtil.cancel(DynamicHttpConsts.DYNAMIC_GETNEW)
    }

    /**
     * 滑动列表判断是否有音视频播放
     * @param recyclerView RecyclerView?
     */
    private fun autoPlayVideo(recyclerView: RecyclerView?) {
        var is_ture = false
        for (i in 0 until visibleCount) {//拿到显示在屏幕的item
            KLog.e("tag", "循环$i")
            if (recyclerView != null && recyclerView.getChildAt(i) != null) {
                if (recyclerView.getChildAt(i).findViewById<View>(R.id.video_view) != null) {//如果有视频view

                    val homeGSYVideoPlayer = recyclerView.getChildAt(i).findViewById<TXCloudVideoView>(R.id.video_view)
                    val rect = Rect()
                    homeGSYVideoPlayer.getLocalVisibleRect(rect)
                    val videoheight = homeGSYVideoPlayer.height
                    KLog.e("tagss","top"+rect.top+"bottom"+rect.bottom+"left"+rect.left+"right"+rect.right)

                    if (rect.top>=0&&(rect.bottom-rect.top)>150 && rect.bottom == videoheight) {//判断视频在屏幕的位置
                        is_ture = true
                        if (mPlayer?.isPlaying == true && flvUrl == homeGSYVideoPlayer.tag.toString()) {
                            //如果视频正在播放并且url地址相同
                        } else {
                            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                                rl_community_audio?.stopVoice()
                            }
                            mPlayer?.stopPlay(true)
                            mPlayer?.setPlayerView(homeGSYVideoPlayer)
                            mPlayer?.setAutoPlay(true)
                            mPlayer?.isLoop = true
                            flvUrl = homeGSYVideoPlayer.tag.toString()
                            if (is_Activity) {
                                mPlayer?.startPlay(flvUrl)
                            }
                            mPlayer?.setVodListener(object : ITXVodPlayListener {
                                override fun onPlayEvent(player: TXVodPlayer?, event: Int, param: Bundle?) {
                                    KLog.e("tag", event)
                                    if (event === TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
                                        homeGSYVideoPlayer.bringToFront()
                                    }
                                }

                                override fun onNetStatus(p0: TXVodPlayer?, p1: Bundle?) {
                                    KLog.e("tag", p1.toString())
                                }
                            })
                        }
                        break
                    }
                }
//                //判断是否有音频view
//                if (null != recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio) && null != recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio).tag) {
//                    if (is_Activity) {
//                        rl_community_audio?.stopVoice()
//                        rl_community_audio?. resetView()
//                        rl_community_audio?. release()
//                        is_ture = true
//                        mPlayer?.stopPlay(true)
//                        rl_community_audio = recyclerView.getChildAt(i).findViewById<AudioMp3View>(R.id.rl_community_audio)
//                        rl_community_audio?.playVoice(recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio).tag.toString())
//                        if(communityDynamicAdapter.itemCount<firstVisibleItem + i - 1){
//                            communityDynamicAdapter.getItem(firstVisibleItem + i - 1).setmVoicePlaying(true)
//                        }else{
//                            if(communityDynamicAdapter.itemCount<firstVisibleItem + i - 2){
//                                communityDynamicAdapter.getItem(firstVisibleItem + i - 2).setmVoicePlaying(true)
//                            }
//                        }
//                        KLog.e("tag", firstVisibleItem.toString() + "i=" + i)
//                    }
//                    break
//                }
            }
        }
        if (!is_ture) {
            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                rl_community_audio?.stopVoice()
            }
            mPlayer?.stopPlay(true)
        }
    }

    private var rl_community_audio = activity?.let { AudioMp3View(it, "") }

    private val itemChildClickListener = OnItemChildClickListener { adapter, view, position ->
        if(communityDynamicAdapter.getItem(position).isgg.equals("CPM")){
            if(!communityDynamicBeans[position].jump_url.equals("")){
                WebViewActivity.forwars(activity, communityDynamicBeans[position].jump_url)
            }
            return@OnItemChildClickListener
        }
        val id = view.id
        if (id == R.id.rl_community_audio) {
            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                rl_community_audio?.stopVoice()
            }
            mPlayer?.stopPlay(true)
            flvUrl = ""
            if (communityDynamicAdapter.getItem(position).ismVoicePlaying()) {
                communityDynamicAdapter.getItem(position).setmVoicePlaying(false)
            } else {
                rl_community_audio=  view as AudioMp3View
                rl_community_audio?.playVoice(view.tag.toString())
                communityDynamicAdapter.getItem(position).setmVoicePlaying(true)
            }
        } else if (id == R.id.tv_tip) {//撩一下
           // puulLedThe(communityDynamicAdapter.getItem(position).uid)
            setCommunityAttention(position)
        } else if (id == R.id.tv_comment) {//请你发言
            is_Activity = false
            my_position = position
            val intent = Intent(activity, DynamicDetailsActivity::class.java)
            intent.putExtra(Constants.DYNAMIC_BEAN, communityDynamicBeans[position])
            intent.putExtra("position", position.toString() + "")
            startActivityForResult(intent, 7)
        } else if (id == R.id.iv_love) {//关注
            //CommonHttpUtil.setAttention(communityDynamicBeanList.get(position).getUid(), null);
            setCommunityAttention(position)
        } else if (id == R.id.tv_like) {//点赞
            addLike(communityDynamicAdapter.getItem(position).id,
                    communityDynamicAdapter.getItem(position).uid, position, view)
        } else if (id == R.id.iv_logo) {//头像点击
            is_Activity = false
            activity?.let {
                UserCenterActivity.forward(it, communityDynamicAdapter.getItem(position).uid)
            }
        } else if (id == R.id.im_gd) {
//            arrayList.clear()
//            arrayList.add("举 报")
//            arrayList.add("取 消")
//            (activity as AbsDynamicActivity).showpop(view, arrayList, communityDynamicBeans[position].id)
            (activity as AbsDynamicActivity).setting(communityDynamicBeans[position])
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 7) {
            try {
                communityDynamicAdapter.getItem(my_position).comments = data?.extras?.getString("second")
                communityDynamicAdapter.getItem(my_position).islike = data?.extras?.getString("islike")
                communityDynamicAdapter.getItem(my_position).likes = data?.extras?.getString("likes")
                communityDynamicAdapter.getItem(my_position).isattent = data?.extras?.getInt("isattent",0)!!
                communityDynamicBeans[my_position].comments = data.extras?.getString("second")
                try {
                    val a = Integer.parseInt(data.extras?.getString("islike"))
                    communityDynamicBeans[my_position].islike = a.toString()
                } catch (e: NumberFormatException) {
                    e.printStackTrace()
                }
                communityDynamicBeans[my_position].likes = data.extras?.getString("likes")
                communityDynamicAdapter.notifyItemChanged(my_position + 1)
            } catch (e: NullPointerException) {
            }
        }
    }

    /**
     * 关注
     */
    private fun setCommunityAttention(position: Int) {
        CommonHttpUtil.setCommunityAttention(communityDynamicAdapter.getItem(position).uid,
                object : HttpCallback() {
                    override fun onSuccess(code: Int, msg: String,info: String) {
                        if (code == 0) {
                            val result = PitUtil.strGetFirst(info)

                            val obj = JSON.parseObject(result)
                            //                    EventBus.getDefault().post(new DynamicLikeEvent(dynamicBean.getId(), obj.getIntValue("islike"), obj.getString("nums")));
                            val isattent = obj.getInteger("isattent")
                            communityDynamicAdapter.getItem(position).isattent = isattent
                            communityDynamicAdapter.notifyItemChanged(position)
                        } else {
                            ToastUtil.show(msg)
                        }
                        communityDynamicAdapter.notifyItemChanged(position)
                    }
                })
    }

    /**
     * 撩一下
     */
    private fun puulLedThe(uid: String) {
        MainHttpUtil.pulledThe(uid, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    val inflater = layoutInflater
                    val view1 = inflater.inflate(R.layout.dialog_tips_layout, null)
                    val textView = view1.findViewById<TextView>(R.id.tv_dialog_context)
                    textView.text = "成功撩了一下！"
                    activity?.run {
                        var dialog = AutoDismissDialog(this,R.style.DialogStyleTips)
                        dialog.setContentView(view1)
                        dialog.setCanceledOnTouchOutside(true)
                        dialog.show()
                    }
                } else {
                    if(code == 1002){
                        val inflater = layoutInflater
                        val view1 = inflater.inflate(R.layout.dialog_tips_layout, null)
                        val textView = view1.findViewById<TextView>(R.id.tv_dialog_context)
                        val iv_dialog_tips_img = view1.findViewById<ImageView>(R.id.iv_dialog_tips_img)
                        iv_dialog_tips_img.setImageResource(R.mipmap.pic_lyls)
                        textView.text = "糖果不足"
                        activity?.run {
                            var dialog = AutoDismissDialog(this,R.style.DialogStyleTips)
                            dialog.setContentView(view1)
                            dialog.setCanceledOnTouchOutside(true)
                            dialog.show()
                        }
                    }else
                    ToastUtil.show(msg)
                }
            }
        })
    }
    //点赞
    private fun addLike(id: String, uid: String, position: Int, view: View) {
        if (uid == CommonAppConfig.getInstance().uid) {
            ToastUtil.show(WordUtil.getString(com.manor.dynamic.R.string.video_comment_cannot_self))
            return
        }
        DynamicHttpUtil.addLike(id, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    val result = PitUtil.strGetFirst(info)
                    val obj = JSON.parseObject(result)
                    //EventBus.getDefault().post(new DynamicLikeEvent(dynamicBean.getId(), obj.getIntValue("islike"), obj.getString("nums")));
                    val islike = obj.getIntValue("islike")
                    val nums = obj.getString("nums")
                    communityDynamicAdapter.getItem(position).islike = islike.toString() + ""
                    communityDynamicAdapter.getItem(position).likes = nums
                    communityDynamicBeans[position].islike = islike.toString()
                    communityDynamicBeans[position].likes = nums
                    //    communityDynamicAdapter.notifyItemChanged(position+1);
                    val tv_name = view as DrawableTextView
                    if ("1" == communityDynamicAdapter.getItem(position).islike) {
                        tv_name.leftDrawable = activity?.getDrawable(R.mipmap.icon_up)
                        tv_name.text = nums
                    } else if ("0" == communityDynamicAdapter.getItem(position).islike) {
                        tv_name.leftDrawable = activity?.getDrawable(R.mipmap.icon_unup)
                        tv_name.text = nums
                    }
                } else {
                    ToastUtil.show(msg)
                }
            }
        })
    }


    private fun getDynamicList() {
        //拿到当前最后一个数据的值 后台判断不冲突显示
        var lastid = ""
                if (pageNum > 1 && communityDynamicAdapter.data.size > 1) {
                    try {
                lastid = communityDynamicAdapter.data.get(communityDynamicAdapter.data.size - 1).row
            }catch (e:IllegalStateException){
                return
            }

        }
        DynamicHttpUtil.getDynamicList(pageNum, lastid, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info:String) {
                KLog.e("getDynamicList", "拿到数据$pageNum")
                setDate(code, msg, info)
                srl_city.setEnableLoadMore(true)
                srl_city.setEnableRefresh(true)
                is_shuaxin = true


            }

            override fun onError() {
                srl_city.setEnableLoadMore(true)
                srl_city.finishLoadMore()
                srl_city.finishRefresh()
                if (pageNum > 1) {
                    pageNum--
                }
                is_shuaxin = true
                ToastUtil.show("网络请求失败")
                super.onError()
            }
        })
    }

    var communityDynamicBeans: MutableList<CommunityDynamicBean> = ArrayList()
    private fun setDate(code: Int, msg: String, info: String) {
        if (code == 0) {
            if (info.isNotEmpty()) {
                if (pageNum > 1) {//加载
                    val communityDynamic = JSON.parseArray(info, CommunityDynamicBean::class.java)
                    communityDynamicAdapter.addData(communityDynamic)
                    communityDynamicBeans.addAll(communityDynamic)
                    srl_city?.finishLoadMore()
                } else {//刷新
                    if (communityDynamicBeans.size > 0) {
                        communityDynamicBeans.clear()
                    }
                    val communityDynamic = JSON.parseArray(info, CommunityDynamicBean::class.java)
                    communityDynamicBeans.addAll(communityDynamic)
                    communityDynamicAdapter.setNewInstance(communityDynamic)
                    //                    communityDynamicAdapter.setNewInstance(communityDynamicBeanList);
                    srl_city?.finishRefresh()
                }
            } else {
                srl_city?.finishLoadMore()
                srl_city?.finishRefresh()
                srl_city?.finishLoadMoreWithNoMoreData()
            }
        } else {
            srl_city?.finishLoadMore()
            srl_city?.finishRefresh()
            ToastUtil.show(msg)
        }

        if (communityDynamicAdapter.data.isNullOrEmpty()){
            communityDynamicAdapter.setEmptyView(R.layout.view_empty_default)
        }

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        KLog.e("tag", hidden.toString())
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        is_Activity = isVisibleToUser
        if(!isVisibleToUser){
            if (cityRefresh) {
                mPlayer?.stopPlay(true)
                flvUrl = ""
                rl_community_audio?.stopVoice()
            }
        }
        KLog.e("tag", isVisibleToUser.toString())
    }

    override fun bindEvent() {
    }

    override fun onClick(v: View?) {
    }

    override fun initData() {
    }

    override fun initImmersionBar() {
    }

    override fun immersionBarEnabled(): Boolean {
        return false
    }

    override fun initView() {
    }
}